//
//  DetailViewController.m
//  KeepFit
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "DetailViewController.h"
#import "GroupCell.h"
#import "ResultCVCell.h"
#import "FoodDetail.h"
#import <MBProgressHUD.h>
#import "FinalViewController.h"
#import "UILabel+NightVersion.h"
@interface DetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, tableViewDelegate, MBProgressHUDDelegate>

@property (nonatomic, strong) UICollectionView *groupCollectionView; // 上面的4个button
@property (nonatomic, strong) UICollectionView * resultCollectionView;
@property (nonatomic, strong) UIView *lightView;

@property (nonatomic, strong) NSArray *groupArr;
@property (nonatomic, strong) NSMutableArray *jianArr;

@property (nonatomic, strong) NSMutableArray *foodResultArr;  //  食物结果数组
@property (nonatomic, strong) NSMutableArray *groupStatusArr; //  营养类别顺序数组
@property (nonatomic, assign) NSInteger groupIndex;          //  类别下标(@"常见",@"热量",@"蛋白质",@"脂肪",)
@property (nonatomic, strong) NSMutableDictionary *sortStatusDic;   //  使下标和排序状态(0降序,1升序)一一对应的字典
@property (nonatomic, assign) NSInteger previousIndex;      //  前一个高亮条下标
@property (nonatomic, assign) NSInteger currentPage;



@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonAction:)];
    self.foodResultArr = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UICollectionViewFlowLayout *groupFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    groupFlowLayout.itemSize = CGSizeMake(self.view.bounds.size.width / 4, 40);
    groupFlowLayout.minimumLineSpacing = 1;
    groupFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 种类collectionView
    self.groupCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40) collectionViewLayout:groupFlowLayout];
    [self.view addSubview:self.groupCollectionView];
    self.groupCollectionView.delegate = self;
    self.groupCollectionView.dataSource = self;
    self.groupCollectionView.backgroundColor = [UIColor whiteColor];
    self.groupCollectionView.contentOffset = CGPointMake(0, 0);
    // 红线
    self.lightView = [[UIView alloc] initWithFrame:CGRectMake(0, self.groupCollectionView.bounds.size.height - 2, self.groupCollectionView.bounds.size.width / 4, 2)];
    self.lightView.backgroundColor = [UIColor redColor];
    [self.groupCollectionView addSubview:self.lightView];
   
    UINib *nib = [UINib nibWithNibName:@"GroupCell" bundle:[NSBundle mainBundle]];
    [self.groupCollectionView registerNib:nib forCellWithReuseIdentifier:@"group"];
    
    UICollectionViewFlowLayout *resultFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    resultFlowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 40);
    resultFlowLayout.minimumLineSpacing = 0;
    resultFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.resultCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 40) collectionViewLayout:resultFlowLayout];
    
    self.resultCollectionView.pagingEnabled = YES;
    self.resultCollectionView.delegate = self;
    self.resultCollectionView.dataSource = self;
    self.resultCollectionView.showsVerticalScrollIndicator = NO;
    self.resultCollectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.resultCollectionView];
    
    [self.resultCollectionView registerClass:[ResultCVCell class] forCellWithReuseIdentifier:@"result"];
    self.groupIndex = 1;
    
    // group每个类别对应的箭头
    self.groupArr = @[@"常见",@"热量",@"蛋白质",@"脂肪"];
    self.jianArr = [NSMutableArray arrayWithObjects:@"",@"↑",@"↓",@"↑", nil];
    
    // group接口拼接拼接的key和value(0代表从低到高,箭头向下, 1代表从高到低,箭头向上), 第一个没有排序
    NSArray *keys = @[@"1",@"2",@"3",@"4"];
    NSArray *values = @[@"0",@"1",@"0",@"1"];
    // 生成一个对应的字典
    self.sortStatusDic = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
        

    
    
}
//  点击按钮
- (void)leftBarButtonAction:(UIBarButtonItem *)bnt
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
    
}
#pragma mark ---每个组的cell-----
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.groupCollectionView) {
        GroupCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"group" forIndexPath:indexPath];
        cell.hahaLab.text = [NSString stringWithFormat:@"%@%@",[self.groupArr objectAtIndex:indexPath.row],[self.jianArr objectAtIndex:indexPath.row]];
        if (indexPath.item == self.groupIndex - 1)
        {
            cell.hahaLab.textColor = [UIColor redColor]; //  关键字高亮
        }
        else
        {
            cell.hahaLab.textColor = [UIColor blackColor];
//            [cell.hahaLab nightVersion];
            //  默认黑色(防止重用变红)
        }
        return cell;
        
    }else{
        ResultCVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"result" forIndexPath:indexPath];
        self.groupIndex = indexPath.item + 1;
        NSString *key = [NSString stringWithFormat:@"%ld",self.groupIndex];
        cell.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?order_asc=%@&value=%@&kind=group&order_by=%ld",[self.sortStatusDic objectForKey:key],self.detailId,self.groupIndex];
        self.previousIndex = indexPath.item;
        cell.groupIndex = self.groupIndex;
        cell.pushdelegate = self;
        cell.current_page = self.currentPage;
        if (cell.current_page == 1)
        {
            cell.commonResultArr = [NSMutableArray array];
            cell.caloryResultArr = [NSMutableArray array];
            cell.proteinResultArr = [NSMutableArray array];
            cell.fatResultArr = [NSMutableArray array];
        }
        [cell loadData];
        
        return cell;

        
    }
    
}

#pragma mark -----group底部红线滑动的方法--------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
        self.lightView.frame = CGRectMake(self.resultCollectionView.contentOffset.x / self.groupCollectionView.bounds.size.width * self.view.bounds.size.width / 4, self.groupCollectionView.bounds.size.height - 2, self.view.bounds.size.width / 4, 2);
    
    
    CGFloat page = self.resultCollectionView.contentOffset.x / self.groupCollectionView.bounds.size.width;
    if (page == 1.0 || page == 2.0 || page == 3.0 || page == 0.0)
    {
        self.groupIndex = self.resultCollectionView.contentOffset.x / self.groupCollectionView.bounds.size.width + 1;   //  关键字高亮
        [self.groupCollectionView reloadData];
    }
    
    
   
}

#pragma mark -----加载数据的方法-----
- (void)handleData
{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.color = [UIColor colorWithRed:0.13 green:0.10 blue:0.10 alpha:0.9];
    hub.removeFromSuperViewOnHide = YES;
    
    hub.delegate = self;
    hub.labelText = @"得之我幸,失之我命,如此安好...";
    
    NSString *key = [NSString stringWithFormat:@"%ld",self.groupIndex];
    NSString *urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?order_asc=%@&value=%@&kind=group&order_by=%ld",[self.sortStatusDic objectForKey:key],self.detailId,self.groupIndex];
   [NetWorkingCache getUrl:urlStr success:^(id result) {
       NSArray *resultArr = [result objectForKey:@"foods"];
       for (NSDictionary *dic in resultArr) {
           FoodDetail *foodDetail = [FoodDetail modelWithDic:dic];
           [self.foodResultArr addObject:foodDetail];
       }
       [self.resultCollectionView reloadData];
       self.currentPage = 1;
       [self.groupCollectionView reloadData];
       [hub hide:YES];
       
   } failure:^(NSError *error) {
       
   }];
   
}

#pragma mark ----groupCell点击方法----
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath //  营养类别CollectionViewCell点击方法
{
    if (indexPath.item == self.previousIndex)
    {
        
        if (indexPath.item != 0)    //  排序
        {
            
            NSString *key = [NSString stringWithFormat:@"%ld",indexPath.item + 1];
            NSString *valueP = [self.sortStatusDic objectForKey:key];
            BOOL status = [valueP integerValue];
            NSLog(@"=======%ld", [valueP integerValue]);
            if ([valueP integerValue] == 1)
            {
                [self.jianArr replaceObjectAtIndex:indexPath.item withObject:@"↓"];
            }
            else
            {
                [self.jianArr replaceObjectAtIndex:indexPath.item withObject:@"↑"];
                
            }
            [self.groupCollectionView reloadItemsAtIndexPaths:@[indexPath]];
            
            NSString *value = [NSString stringWithFormat:@"%d",!status];

            [self.sortStatusDic setObject: value forKey:key];
            ResultCVCell *cellResult = (ResultCVCell *)[self.resultCollectionView cellForItemAtIndexPath:indexPath];
            cellResult.tableView.contentOffset = CGPointMake(0, 0);
            [self handleData];
        }
    }
    else
    {
     
        self.groupIndex = indexPath.item + 1;   //  切换类别
        self.resultCollectionView.contentOffset = CGPointMake(self.view.bounds.size.width * indexPath.item, 0);
        
        
        [self handleData];
    }
 
}

#pragma mark 协议方法 -------
- (void)pushFoodVCWithStr:(NSString *)str
{
    FinalViewController *finalVC = [[FinalViewController alloc] init];
    finalVC.foodCode = str;
    
    [self.navigationController pushViewController:finalVC animated:YES];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
